package per.turtle.websocket.endpoint;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import per.turtle.common.redis.service.RedisService;
import per.turtle.websocket.domain.Message;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yuj
 */
@Component
@RequiredArgsConstructor
@ServerEndpoint("/msg/{userToken}")
public class WebSocketServer {

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
     */
    public static final String SESSION_POOLS = "web_socket_session_pool";

    /**
     * 群发消息
     */
    private static final String SEND_TO_ALL = "S2A";

    /**
     * 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
     */
    private static final AtomicInteger ONLINE_NUM = new AtomicInteger();

    @Autowired
    private final RedisService redisService;

    private final ObjectMapper jsonMapper = new ObjectMapper();

    public static void addOnlineCount() {
        ONLINE_NUM.incrementAndGet();
    }

    public static void subOnlineCount() {
        ONLINE_NUM.decrementAndGet();
    }

    /**
     * 群发消息
     *
     * @param message 消息
     */
    public void broadcast(String message) {
        for (Object session : redisService.getCacheMap(SESSION_POOLS).values()) {
            try {
                sendMessage((Session) session, message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭连接时调用
     *
     * @param userName 用户名
     */
    @OnClose
    public void onClose(@PathParam(value = "userToken") String userName) throws JsonProcessingException {
        Map<String, Object> map = redisService.getCacheMap(SESSION_POOLS);
        map.remove(userName);
        redisService.setCacheMap(SESSION_POOLS, map);
        subOnlineCount();
        System.out.println(userName + "断开webSocket连接！当前人数为" + ONLINE_NUM);
        // 广播下线消息
        Message msg = new Message();
        msg.setDate(new Date());
        msg.setTo("-2");
        msg.setText(userName);
        broadcast(jsonMapper.writeValueAsString(msg));
    }

    /**
     * 错误时调用
     *
     * @param session   会话
     * @param throwable 异常
     */
    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("发生错误" + throwable.getMessage());
    }

    /**
     * 收到客户端信息后，根据接收人的username把消息推下去或者群发
     *
     * @param message 消息
     */
    @OnMessage
    public void onMessage(String message) throws JsonProcessingException {
        System.out.println("server get" + message);
        Message msg = jsonMapper.readValue(message, Message.class);
        msg.setDate(new Date());
        if (SEND_TO_ALL.equals(msg.getTo())) {
            broadcast(jsonMapper.writeValueAsString(msg));
        } else {
            sendInfo(msg.getTo(), jsonMapper.writeValueAsString(msg));
        }
    }

    /**
     * 建立连接成功调用
     *
     * @param session  会话
     * @param userName 用户名
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userToken") String userName) throws JsonProcessingException {
        redisService.setCacheMapValue(SESSION_POOLS, userName, session);
        addOnlineCount();
        System.out.println(userName + "加入webSocket！当前人数为" + ONLINE_NUM);
        // 广播上线消息
        Message msg = new Message();
        msg.setDate(new Date());
        msg.setTo("0");
        msg.setText(userName);
        broadcast(jsonMapper.writeValueAsString(msg));
    }

    /**
     * 给指定用户发送信息
     *
     * @param userName 用户名
     * @param message  消息
     */
    public void sendInfo(String userName, String message) {
        Session session = redisService.getCacheMapValue(SESSION_POOLS, userName);
        try {
            sendMessage(session, message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送消息
     *
     * @param session 会话
     * @param message 消息
     * @throws IOException 异常
     */
    public void sendMessage(Session session, String message) throws IOException {
        if (session != null) {
            System.out.println("发送数据：" + message);
            session.getBasicRemote().sendText(message);
        }
    }

}
